package com.meituan.verintreport.task;

import com.meituan.verintreport.db.dao.DirectSqlDAO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 *直接执行目录下sql语句的
 */
@Slf4j
@Component
@ConfigurationProperties(prefix = "sqlscripts")
@Data
public class RunSqlScripts {
    private String path;

    private boolean enable;

    @Autowired
    private DirectSqlDAO directSqlDAO;

    @Scheduled(cron = "${sqlscripts.cron}")
    public void execute() {
        if (!isEnable()) {
            return;
        }

        try {
            File folderPath = new File(path);
            if (!folderPath.exists() || !folderPath.isDirectory()) {
                log.error("Config sqlscripts.path is not correct");
                return;
            }

            File[] files = folderPath.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith(".sql");
                }
            });

            for (File file : files) {
                log.info("start file: {}", file);
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String line = reader.readLine();
                int rowCount = 1;
                do {
//                    log.info(line);
                    if (line.trim().length() > 10) {
                        line = line.replaceAll("\\uFEFF", "");
                        try {
                            int affectRows = directSqlDAO.update(line);
                            rowCount ++;
                        } catch (Exception e) {
                            log.error("Execute sql error. sql: {}", line, e);
                        }
                    }

                    if (rowCount % 1000 == 0) {
                        log.info("Current sql row: {}.", rowCount);
                    }
                    line = reader.readLine();
                } while (line != null);

                log.info("total rows: {}", rowCount);
                log.info("end file: {}", file);
                reader.close();
            }

            log.info("Done");
            enable = false;
        } catch (Exception e) {
            log.error("Can't get sql session template for report", e);
        }
    }
}
